import store from './platform/StorageUtil';
import EosClient from "./EosChainClient";

let wallets_key = 'wallets_test1';
let default_wallet_key = 'defaultWallet_test1';

const walletsDataFormat = ()=>{
    let wallets = [
        {
            name:'',
            password:'',
            salt:'',
            privateKey:'',
            publicKey:'',
            words:'',
            accountName:'zuowen123123',
            accounts:[],
            data:[]
        },
        {

        }
    ];

    let defaultWallet = {
        name:'',
        password:'',
        salt:'',
        privateKey:'',
        publicKey:'',
        words:'',
        accountName:'zuowen123123',
        account:{
            name:'',
            balance:{},
            cpu:{}
        }
    }
};

const get = (payload,callback) => {
    store.get(wallets_key,(wallets)=>{
        if(!wallets){
            wallets = [];
        }

        for(let i=0; i<wallets.length; i++){
            let wallet = wallets[i];
            if(wallet.publicKey === payload.publicKey){
                if(callback) callback(wallet);
                // console.log('local wallets get: ' + JSON.stringify(wallet));
            }
        }
    });
};

const list = (callback) => {
    store.get(wallets_key,(wallets)=>{
        if(wallets === null){
            wallets = [];
        }
        if(callback) callback(wallets);
        // console.log('local wallets list: ' + JSON.stringify(wallets));
    });
};

const create = (payload,callback) => {
    let wallet = payload;
    store.get(wallets_key,(wallets)=>{
        if(wallets === null){
            wallets = [];
        }

        if(wallets.length === 0){
            //创建第一个钱包，设置为默认钱包
            console.log('defaultWallet check after create: ' + JSON.stringify(wallet));
            updateDefaultWallet(payload,(wallet)=>{});
        }

        let count = wallets.length+1;
        wallet.index = count;
        if(!wallet.name){
            wallet.name = 'Wallet'+count;
        }
        if(wallets.contains(wallet.name)){
            return;
        }
        wallets.push(wallet);

        //console.log('local wallets create: ' + JSON.stringify(wallet));
        store.save(wallets_key,wallets,(storeWallets)=>{
            console.log('local wallets check after create: ' + JSON.stringify(storeWallets));
            if(callback) callback(storeWallets);
        });
    });
};

const del = (payload,callback) => {
    store.get(wallets_key,(wallets)=>{
        if(!wallets){
            wallets = [];
        }

        //删除某个钱包
        for(let i=0; i<wallets.length; i++){
            let wallet = wallets[i];
            if(wallet.publicKey === payload.publicKey){
                wallets.splice(i,1);
                break;
            }
        }

        //删除了默认钱包
        getDefaultWallet((def)=>{
            if(def.publicKey === payload.publicKey){
                console.log('del default wallet');
                delDefaultWallet((def)=>{
                    if(wallets.length===1){
                        let defWallet = wallets[0];
                        console.log('del default wallet , reset default wallet');
                        //公钥获取账号
                        EosClient.getKeyAccounts(defWallet.publicKey,(accounts)=>{
                            if(!!accounts && accounts.length>0){
                                defWallet.accountName = accounts[0].name;
                                // console.log('defaultWallet check after delete: ' + JSON.stringify(wallet));
                                updateDefaultWallet(defWallet,(wallet)=>{});
                            }
                        })

                    }
                });
            }
        });

        store.save(wallets_key,wallets,(storeWallets)=>{
            // console.log('local wallets check after delete: ' + JSON.stringify(storeWallets));
            if(callback) callback(storeWallets);
        });


    });
};

const update = (payload,callback) => {
    store.get(wallets_key,(wallets)=>{
        if(wallets === null){
            wallets = [];
        }

        for(let i=0; i<wallets.length; i++){
            if(wallets[i].publicKey === payload.publicKey){
                wallets[i] = {...wallets[i],...payload};
                //console.log('local wallets update: ' + JSON.stringify(wallets[i]));
                //if (callback) callback(wallets[i]);
                break;
            }
        }
        store.save(wallets_key,wallets,(storeWallets)=>{
            // console.log('local wallets check after update: ' + JSON.stringify(storeWallets));
            if(callback) callback(storeWallets);
        });
    });
};

const clear = () => {
    store.delete(wallets_key,(storeWallets)=>{
        // console.log('local wallets check after clear: ' + JSON.stringify(storeWallets));
    });
};

const exist = (payload,callback) => {
    store.get(wallets_key,(wallets)=>{
        if (!wallets) {
            wallets = [];
            if (callback) callback({ exist:false});
            return;
        } else if (wallets.length >= 10) {
            if (callback) callback({ exist:true});
            return;
        }
        for(let i=0; i<wallets.length; i++){
            let wallet = wallets[i];
            if(wallet.publicKey === payload.publicKey){
                if (callback) callback({ exist:true});
                return;
            }
        }
        if (callback) callback({ exist:false});
    });
};

const delDefaultWallet = (callback) => {
    store.del(default_wallet_key,(wallet)=>{
        console.log('defaultWallet delete : '+JSON.stringify(wallet));
        if(callback){callback()}
    });
};

const updateDefaultWallet = (payload, callback) => {
    store.get(default_wallet_key,(wallet)=>{
        if(!wallet){
            wallet = {};
        }
        wallet = {...wallet,...payload};
        store.save(default_wallet_key,wallet,(wallet)=>{
            console.log('defaultWallet check after update: ' + JSON.stringify(wallet));
            if(callback) callback(wallet);
        });
    });
};

const getDefaultWallet = (callback) => {
    let defaultWallet = {
        name:'wallet1',
        accountName:'zuowen123123'

    };
    store.get(default_wallet_key,(wallet)=>{
        // console.log('local wallets get DefaultWallet: ' + JSON.stringify(wallet));
        if(wallet && wallet.name){
            if(callback) callback(wallet);
        }else{
            store.get(wallets_key,(wallets)=>{
                if(!wallets){
                    wallets = [];
                }
                if(wallets.length>0){
                    let def = wallets[0];
                    if(callback) callback(def);
                }else{
                    if(callback) callback(null);
                }
            });
        }
    });
};

const getDefaultWalletData = (callback,cache=true) => {
    getDefaultWallet((wallet)=>{
        if(!wallet || !wallet.accountName){
            if(callback) callback(wallet);
            return;
        }

        EosClient.getAccount(wallet.accountName,(data)=>{
            wallet.account = data;
            if(callback) callback(wallet);
            // console.log('local wallets get getDefaultWalletData: ' + JSON.stringify(wallet));
        },cache);
    });
};

const checkDefaultWallet = (callback) => {
    store.get(default_wallet_key,(wallet)=>{
        if(wallet && wallet.accountName){
            if(callback) callback(true);
        }else {
            if(callback) callback(false);
        }
    });
};

export default {
    get,
    list,
    del,
    update,
    create,
    clear,
    exist,
    delDefaultWallet,
    updateDefaultWallet,
    getDefaultWallet,
    getDefaultWalletData,
};